import publicForm from "@/components/public/el-form.vue"; //弹框form
import TableData from '@/components/public/el-tables'; //列表
import formJs from "./regexDetail.js"; //新增弹框配置项

import {
    getSteelProtectionTestTaskData, //详情
    getBaseDepartmentUser, //选择人
    saveSteelProtectionTestTaskData, //保存
    checkSteelProtectionTestTaskData, //审核保存
} from "@/api/request.js";
export default {
    props: [
        "dialogVisible",
        "dialogTitle",
        "statusNum",
        "currentRow",
        "tableTitle",
        "typeDataShow"
    ],
    //
    data() {
        return {
            visible: "",
            title: null,
            dialogHeight: null,
            rowData: null,
            formData: {
                fAdditionaldescription: null,
            },
            loading: false,
            timeYMD: "",
            timeYmdHms: "",
            // 页签切换
            typeData: [{
                text: "钢筋保护层厚度试验检测记录表",
                show: true
            },
            {
                text: "钢筋保护层厚度试验检测报告",
                show: false
            },
            {
                text: "审批流程",
                show: false
            },
            ],
            // 记录表
            recordTableObj: formJs.recordTableObj, //表格基础信息
            associatedObj: formJs.associatedObj, //设计值、允许偏差、修正因子
            measurePointObj: formJs.measurePointObj, //测点部位
            formList: [], //50个测点
            recordTableBottomObj: formJs.recordTableBottomObj, //检测点数、合格、合格率
            sgDisabled: false, //施工单位--是否可编辑
            jlDisabled: false, //监理单位--是否可编辑
            personList: null, // 底部
            perDisabled: false, //记录人、复核人是否可编辑--底部
            buttonShow: true, //按钮显示
            isLock: false, //按钮是否可用
            designValue: 0, //保护层厚度设计值--计算
            deviationValue: 0, //允许偏差值--计算+
            deviationValue1: 0, //允许偏差值--计算-
            correctValue: 0, //修正因子--计算
            // 记录表

            // 检测报告
            testReportObj: formJs.testReportObj, //表格基础信息
            MaxAndMinObj: formJs.MaxAndMinObj, //最大值、最小值
            // 检测报告

            // 审批流程
            table_config: formJs.table_config, //列表
            tableData: [],
            // 审批流程



        };
    },
    components: {
        publicForm,
        TableData, //主页面列表
    },
    watch: {
        dialogVisible: {
            handler(newVal) {
                if (newVal) {
                    this.visible = newVal;
                }
            },
            immediate: true,
        },
        dialogTitle: {
            handler(newVal) {
                if (newVal) {
                    this.title = newVal;
                }
            },
            immediate: true,
        },
        currentRow: {
            handler(newVal) {
                if (newVal) {
                    this.rowData = newVal;
                    this.getDetail({
                        fId: this.rowData.fId
                    })
                    this.getPerson(this.rowData.fCompanyid);
                }
            },
            immediate: true,
        },
        typeDataShow: {
            handler(newVal) {
                if (newVal) {
                    if (newVal == "0") {
                        this.typeData[0].show = true;
                        this.typeData[1].show = false;
                        this.typeData[2].show = false;
                    } else {
                        this.typeData[0].show = false;
                        this.typeData[1].show = true;
                        this.typeData[2].show = false;
                    }
                }
            },
            immediate: true,
        },
    },
    created() {
        window.addEventListener("resize", this.getHeight);
        this.getHeight();
    }, //获取页面高度自适应：

    destroyed() {
        window.removeEventListener("resize", this.getHeight);
        this.getHeight();
    },
    mounted() {
        this.userInfo = JSON.parse(sessionStorage.getItem("yjSmart-userInfo"));
        this.getHeight();
        this.getData();
    },
    methods: {
        moveFocus(event, index, i, num) {
            var text;
            if (event.code == "ArrowRight") {
                if (num == 1) {
                    text = index + 'fParam' + i + 'gb2'
                    this.$refs[text][0].focus();
                } else if (num == 2) {
                    if (i < 9) {
                        text = index + 'fParam' + (i + 1) + 'gb1'
                        this.$refs[text][0].focus();
                    } else if (i == 9) {
                        if (index < 4) {
                            text = (index + 1) + 'fParam' + 0 + 'gb1'
                            this.$refs[text][0].focus();
                        }

                    }
                }
            } else if (event.code == "ArrowLeft") {
                if (num == 2) {
                    text = index + 'fParam' + i + 'gb1'
                    this.$refs[text][0].focus();
                } else if (num == 1) {
                    if (0 < i && i < 10) {
                        text = index + 'fParam' + (i - 1) + 'gb2'
                        this.$refs[text][0].focus();
                    } else if (i == 0) {
                        if (index != 0) {
                            text = (index - 1) + 'fParam' + '9gb2'
                            this.$refs[text][0].focus();
                        }

                    }
                }
            }
            if (event.keyCode === 13) {
                // 回车
                if (num == 1) {
                    text = index + 'fParam' + i + 'gb2'
                    this.$refs[text][0].focus();
                } else if (num == 2) {
                    if (i < 9) {
                        text = index + 'fParam' + (i + 1) + 'gb1'
                        this.$refs[text][0].focus();
                    } else if (i == 9) {
                        if (index < 4) {
                            text = (index + 1) + 'fParam' + 0 + 'gb1'
                            this.$refs[text][0].focus();
                        }

                    }
                }

            }
        },
        // 页签切换
        changeType(e, index) {
            for (let i in this.typeData) {
                if (parseFloat(i) === index) {
                    this.typeData[i].show = true;
                } else {
                    this.typeData[i].show = false;
                }
            }
        },
        // 详情
        getDetail(obj) {
            this.userInfo = JSON.parse(sessionStorage.getItem("yjSmart-userInfo"));
            this.loading = true;
            getSteelProtectionTestTaskData(obj).then((res) => {
                if (res.errcode == 0) {
                    this.loading = false;
                    // this.perDisabled = true;
                    this.sgDisabled = true;
                    this.jlDisabled = true;
                    this.buttonShow = false;
                    var data = res.data.testTask;
                    this.formList = [];

                    if (res.data.testTask.fAdditionaldescription == null) {
                        res.data.testTask.fAdditionaldescription = "";
                    }
                    this.formData = res.data.testTask;
                    this.tableData = res.data.taskList;

                    // 记录表
                    this.designValue = Number(this.formData.fThicknessdesignvalue); // 保护层厚度设计值
                    this.deviationValue = Number(this.formData.fAllowdeviation); // 允许偏差值+
                    this.deviationValue1 = Number(this.formData.fAllowdeviation1); // 允许偏差值-
                    this.correctValue = Number(this.formData.fCorrectionfactor); // 修正因子

                    this.recordTableObj.map(item => {
                        var name = item.value;
                        item['key'] = data[name];
                    })
                    var DataArr = this.formData.fPlantestdates.split("-");
                    var Plantestdate = DataArr[0] + "年" + DataArr[1] + "月" + DataArr[2] + "日";
                    this.recordTableObj[4].key = Plantestdate;

                    this.associatedObj.map((item, index) => {
                        var name = item.value;
                        if (index == 1) {
                            // item['key'] = "±" + data[name];
                            item['key'] = "+" + data[name];
                        }
                        if (index == 2) {
                            // item['key'] = "±" + data[name];
                            item['key'] = "-" + data[name];
                        } else {
                            item['key'] = data[name];
                        }
                    })

                    this.recordTableBottomObj.map(item => {
                        var name = item.value;
                        item['key'] = data[name];
                    })
                      // 检测报告
                      this.testReportObj.map(item => {
                        var name = item.value;
                        item['key'] = data[name];
                    })
                    this.MaxAndMinObj.map(item => {
                        var name = item.value;
                        item['key'] = data[name];
                    })
                    // 检测报告
                    this.formList = [data.checkPointList1, data.checkPointList2, data.checkPointList3, data.checkPointList4, data.checkPointList5];

                    // 自动计算
                    if (this.formData.fThicknessdesignvalue != "" && this.formData.fThicknessdesignvalue != null && this.formData.fAllowdeviation != "" && this.formData.fAllowdeviation != null && this.formData.fAllowdeviation1 != "" && this.formData.fAllowdeviation1 != null && this.formData.fCorrectionfactor != "" && this.formData.fCorrectionfactor != null) {
                        this.inputList();
                    } else {
                        console.log("'保护层厚度设计值'或'允许偏差值'或'修正因子'为空，不能进行重新计算");
                    }
                    // 自动计算

                    if (this.statusNum == 1) { //编辑
                        this.sgDisabled = false;
                        // this.perDisabled = false;
                        this.buttonShow = true;
                        if (this.formData.fCheckername == null || this.formData.fCheckername == "") {
                            this.formData.fCheckername = this.userInfo.realName;
                            this.formData.fCheckerid = this.userInfo.userId;
                        }
                        // 右下角日期
                        if (this.formData.fRecheckdates == null || this.formData.fRecheckdates == "") {
                            this.formData.fRecheckdates = this.formData.fPlantestdates;
                        }
                        // 取样日期
                        if (this.formData.fSampledates == null || this.formData.fSampledates == "") {
                            this.formData.fSampledates = this.timeYMD;
                        }

                    } else if (this.statusNum == 3) { //审核
                        this.jlDisabled = false;
                        // this.perDisabled = false;
                        this.buttonShow = true;
                        this.formData.fJlengineername = this.userInfo.realName;
                        this.formData.fJlengineerid = this.userInfo.userId;
                        // 监理日期
                        if (this.formData.fJlcheckdates == null || this.formData.fJlcheckdates == "") {
                            this.formData.fJlcheckdates = this.timeYMD;
                        }
                    } else if (this.statusNum == 7) {
                        console.log(8);
                    }

                    // 记录表


                  
                } else {
                    this.loading = false;
                    this.$message.error(res.msg);
                }
            });
        },
        getPerson(id) {
            var obj = {
                fCompanyid: id,
            };
            this.personList = []
            getBaseDepartmentUser(obj)
                .then((res) => {
                    if (res.errcode == 0) {
                        var arr = res.data.childList[0].personList;
                        var personList = [];
                        arr.map((item) => {
                            personList.push({
                                label: item.fRealname,
                                value: item.fUserid,
                            });
                        });
                        this.personList = personList

                    } else {
                        this.$message.error(res.msg);
                        return false;
                    }
                })

        },
        selectChange(e, statu) {
            console.log("selectChange", e, statu);
            // 记录人
            if (statu == 0) {
                this.formData.fRecordername = e.label;
                this.formData.fRecorderid = e.value;
            }
            // 复核人
            if (statu == 1) {
                this.formData.fRecheckername = e.label;
                this.formData.fReheckerid = e.value;
            }
        },

        inputFun(e, rowNum, rowIndex, value) {
            // console.log("inputFun", e, rowNum, rowIndex, value);
            // 单值1
            if (value == "1") {
                var value1 = Number(e) + Number(this.correctValue);
                var value2 = Number(this.formList[rowNum][rowIndex].fAmendvalue2);
                this.formList[rowNum][rowIndex].fAmendvalue1 = value1.toString();

                if (this.formList[rowNum][rowIndex].fAmendvalue2 == "/") {
                    this.formList[rowNum][rowIndex].fProtectionthickness = "/";
                } else {
                    if (Math.abs(value1 - value2) > 2) {
                        this.formList[rowNum][rowIndex].fProtectionthickness = "无效";
                    } else {
                        if (Math.abs(value1 - this.designValue) > Math.abs(value2 - this.designValue)) {
                            this.formList[rowNum][rowIndex].fProtectionthickness = value1.toString();
                        } else {
                            this.formList[rowNum][rowIndex].fProtectionthickness = value2.toString();
                        }
                    }
                }
            }
            // 单值2
            if (value == "2") {
                var num1 = Number(this.formList[rowNum][rowIndex].fAmendvalue1);
                var num2 = Number(e) + Number(this.correctValue);
                this.formList[rowNum][rowIndex].fAmendvalue2 = num2.toString();
                if (this.formList[rowNum][rowIndex].fAmendvalue1 == "/") {
                    this.formList[rowNum][rowIndex].fProtectionthickness = "/";
                } else {
                    if (Math.abs(num1 - num2) > 2) {
                        this.formList[rowNum][rowIndex].fProtectionthickness = "无效";
                    } else {
                        if (Math.abs(num2 - this.designValue) > Math.abs(num1 - this.designValue)) {
                            this.formList[rowNum][rowIndex].fProtectionthickness = num2.toString();
                        } else {
                            this.formList[rowNum][rowIndex].fProtectionthickness = num1.toString();
                        }
                    }

                }
            }
            this.totalPoints();
        },

        // 计算
        //列表查看重新计算
        inputList() {
            this.formList.map(item => {
                item.map(v => {
                    if (v.fAmendvalue1 == null || v.fAmendvalue2 == null || v.fAmendvalue1 == "" || v.fAmendvalue2 == "") {
                        if (v.fAmendvalue1 != null && v.fAmendvalue1 != "") {
                            v.fCheckvalue1 == (Number(v.fAmendvalue1) + this.correctValue).toString();
                        }
                        if (v.fAmendvalue2 != null && v.fAmendvalue2 != "") {
                            v.fCheckvalue2 == (Number(v.fAmendvalue2) + this.correctValue).toString();
                        }
                        v.fProtectionthickness == null;
                    } else if (Math.abs(Number(v.fAmendvalue1) - Number(v.fAmendvalue2)) > 2) {
                        v.fCheckvalue1 == (Number(v.fAmendvalue1) + this.correctValue).toString();
                        v.fCheckvalue2 == (Number(v.fAmendvalue2) + this.correctValue).toString();
                        v.fProtectionthickness == "无效";
                    } else {
                        v.fCheckvalue1 == (Number(v.fAmendvalue1) + this.correctValue).toString();
                        v.fCheckvalue2 == (Number(v.fAmendvalue2) + this.correctValue).toString();
                        if ((Number(v.fAmendvalue1) - Number(v.fAmendvalue2)) > 0) {
                            v.fProtectionthickness == v.fCheckvalue1;
                        } else {
                            v.fProtectionthickness == v.fCheckvalue2;
                        }
                    }
                })
            })
            this.totalPoints();
        },

        // 点数，合格点数，合格率计算
        totalPoints() {
            var total = 0; //检测点数
            var qualified = 0; //合格点数
            var Max = this.designValue + this.deviationValue;
            var Min = this.designValue - this.deviationValue1;
            var MaxAndMinArr = []; //保护层厚度--数字数组
            this.formList.map(item => {
                item.map(v => {
                    if (v.fProtectionthickness != "/"&&v.fProtectionthickness !=null&&v.fProtectionthickness !="") {
                        if (v.fProtectionthickness != "无效") {
                            MaxAndMinArr.push(Number(v.fProtectionthickness));
                            if (Min <= Number(v.fProtectionthickness) && Number(v.fProtectionthickness) <= Max) {
                                qualified++;
                            }
                        }
                        total++;
                    }
                })
            })

            //检测点数
            this.recordTableBottomObj[0].key = total.toString();
            //合格点数
            this.recordTableBottomObj[1].key = qualified.toString();
            // 合格率
            if (qualified != 0) {
                this.recordTableBottomObj[2].key = (((qualified / total) * 100).toFixed(2)).toString();
            } else {
                this.recordTableBottomObj[2].key = "0";
            }
            // 最大值/最小值
            this.maxAndMinFun(MaxAndMinArr);
        },

        //最大值，最小值
        maxAndMinFun(arr) {
            let hashTable = {},
                max = 0,
                result = []
            for (let i = 0; i < arr.length; i++) {
                if (!(arr[i] in hashTable)) {
                    hashTable[arr[i]] = 1
                } else {
                    hashTable[arr[i]] += 1
                }
                if (arr[i] > max) {
                    max = arr[i]
                }
            }
            for (let j = 0; j <= max; j++) {
                if (j in hashTable) {
                    for (let i = 0; i < hashTable[j]; i++) {
                        result.push(j)
                    }
                }
            }
            if (result.length != 0) {
                this.MaxAndMinObj[0].key = result[result.length - 1].toString();
                this.MaxAndMinObj[1].key = result[0].toString();
            }
            // if (this.formData.fNote==null) {
        
            //     this.yj_saveForm(this.statusNum,1);
            // }
            return result;
        },
        // 计算

        // 日期选择
        changeData(e, props) {
            if (props == "fJlcheckdates") {
                this.formData.fJlcheckdates = e;
            } else if (props == "fRecheckdates") {
                this.formData.fRecheckdates = e;
            } else if (props == "fSampledates") {
                this.formData.fSampledates = e;
            }
        },
        yj_saveForm(num,status) {
            console.log(this.formData);
            if (num == 1) {
                if (this.formData.fSampledates == "" || this.formData.fSampledates == null) {
                    this.$message.warning("样品信息-取样日期，不能为空");
                    return false;
                }
                // else if (this.formData.fRecordername == "" || this.formData.fRecordername == null) {
                //     this.$message.warning("记录人不能为空");
                //     return false;
                // } else if (this.formData.fRecheckername == "" || this.formData.fRecheckername == null) {
                //     this.$message.warning("复核人不能为空");
                //     return false;
                // } 
                else if (this.formData.fRecheckdates == "" || this.formData.fRecheckdates == null) {
                    this.$message.warning("右下日期不能为空");
                    return false;
                } else if (this.recordTableBottomObj[0].key == "" || this.recordTableBottomObj[0].key == null) {
                    this.$message.warning("测点表格不能为空");
                    return false;
                } else {
                    var saveData = {
                        userId: this.userInfo.userId, // 当前操作用户id
                        userName: this.userInfo.realName, // 当前操作用户名称
                        fId: this.formData.fId, // 数据fid
                        fLabname: this.formData.fLabname, // 试验室名称
                        fSampledates: this.formData.fSampledates, // 取样日期
                        fCheckpointcount: this.recordTableBottomObj[0].key, // 检测点数
                        fQualifiedpointcount: this.recordTableBottomObj[1].key, // 合格点数
                        fQualifiedrate: this.recordTableBottomObj[2].key, // 合格率
                        fAdditionaldescription: this.formData.fAdditionaldescription, // 附加说明
                        fMax: this.MaxAndMinObj[0].key, // 最大值
                        fMin: this.MaxAndMinObj[1].key, // 最小值
                        fCheckerid: this.formData.fCheckerid, // 检测人ID
                        fCheckername: this.formData.fCheckername, // 检测人
                        fRecorderid: this.formData.fRecorderid, // 记录人ID
                        fRecordername: this.formData.fRecordername, // 记录人
                        fReheckerid: this.formData.fReheckerid, // 复核人ID
                        fRecheckername: this.formData.fRecheckername, // 复核人
                        fRecheckdates: this.formData.fRecheckdates, // 右下日期
                        checkPointList1: this.formList[0], // 测点1列表信息
                        checkPointList2: this.formList[1], // 测点2列表信息
                        checkPointList3: this.formList[2], // 测点3列表信息
                        checkPointList4: this.formList[3], // 测点4列表信息
                        checkPointList5: this.formList[4], // 测点5列表信息
                    }
                    // console.log("saveData", saveData);
                    this.editSave(saveData,status);
                }

            } else {
                if (this.formData.fJlopinion == "" || this.formData.fJlopinion == null) {
                    this.$message.warning("监理意见不能为空");
                    return false;
                } else if (this.formData.fJlcheckdates == "" || this.formData.fJlcheckdates == null) {
                    this.$message.warning("监理意见日期不能为空");
                    return false;
                } else {
                    var saveData1 = {
                        fId: this.formData.fId, // 数据fid
                        fJlengineerid: this.formData.fJlengineerid, // 监理人id
                        fJlengineername: this.formData.fJlengineername, // 监理人
                        fJlcheckdates: this.formData.fJlcheckdates, // 监理审核时间
                        fJlopinion: this.formData.fJlopinion, // 监理意见
                        fRecorderid: this.formData.fRecorderid, // 记录人ID
                        fRecordername: this.formData.fRecordername, // 记录人
                        fReheckerid: this.formData.fReheckerid, // 复核人ID
                        fRecheckername: this.formData.fRecheckername, // 复核人
                        userId: this.userInfo.userId, // 当前操作用户id
                        userName: this.userInfo.realName, // 当前操作用户名称
                    }
                    console.log("saveData1", saveData1);
                    this.reviewSave(saveData1);
                }
            }
        },
  
        // 编辑保存
        editSave(obj,status) {
            this.loading = true;
            this.isLock = true
            saveSteelProtectionTestTaskData(obj)
                .then((res) => {
                    if (res.errcode == 0) {
                        this.loading = false;
                        if(status==0){
                            this.$emit("refreshList");
                            this.visible = false;
                            this.$message.success("保存成功");
                        }
                        
                        this.isLock = false
                       
                    } else {
                        this.loading = false;
                        this.isLock = false
                        this.$message.error(res.msg);
                    }
                })
                .catch(() => {
                    console.log("保存接口报错");
                });
        },
        // 审核保存
        reviewSave(obj) {
            this.loading = true;
            this.isLock = true
            checkSteelProtectionTestTaskData(obj)
                .then((res) => {
                    if (res.errcode == 0) {
                        this.loading = false;
                        this.$emit("refreshList");
                        this.isLock = false
                        this.visible = false;
                        this.$message.success("保存成功");
                    } else {
                        this.loading = false;
                        this.isLock = false
                        this.$message.error(res.msg);
                    }
                })
                .catch(() => {
                    console.log("保存接口报错");
                });
        },
        // 时间
        getData() {
            var time = new Date();
            const y = time.getFullYear();
            const m = (time.getMonth() + 1 + "").padStart(2, "0");
            const d = (time.getDate() + "").padStart(2, "0");
            const hh = (time.getHours() + "").padStart(2, "0");
            const mm = (time.getMinutes() + "").padStart(2, "0");
            const ss = (time.getSeconds() + "").padStart(2, "0");
            this.timeYMD = `${y}-${m}-${d}`;
            this.timeYmdHms = `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
        },
        getHeight() {
            var h = document.documentElement.clientHeight; //获取页面可见高度
            this.dialogHeight = h * 1 + "px";
        },
        closeDialog() {
            this.$emit("close");
        },


        // 审批流程
        inputValue(val, table) {
            console.log(val, table);
        },
        // 审批流程


    },
};